/* 
* @Author: ecitlm
* @Date:   2017-05-23 17:59:30
 * @Last Modified by: ecitlm
 * @Last Modified time: 2017-05-26 21:45:49
*/

const express = require('express');
const http    = require('http');
const cheerio = require("cheerio");
const app     = express();
const request = require("request");
const fs      = require('fs');
const Iconv   = require('iconv-lite');
const SSCModel = require('./SSC.js');


function list(req, res) {
    var res = res;
    var req = req;
    var url = 'http://datachart.500.com/ssq/history/newinc/history.php?start=01000&end=17118';
    console.log(url);

    request({
        url: url,
        encoding: 'utf-8'
    }, function (error, response, body) {
        var links = [];
        if (response && response.statusCode == 200) {
            var body = Iconv.decode(body, 'utf-8');
            $ = cheerio.load(body);

            $('#tdata tr').each(function () { 
                var index = 0;   
                var tdArr = [];

                $(this).find('td').each(function(){
                    tdArr[index] = $(this).text();
                    index++;
                });

                console.log("tdArr:" + tdArr);
                if(tdArr instanceof Array && tdArr.length >= 16){
                    var lotteryIndex = parseInt(tdArr[0]);
                    var numRed1 = tdArr[1];
                    var numRed2 = tdArr[2];
                    var numRed3 = tdArr[3];
                    var numRed4 = tdArr[4];
                    var numRed5 = tdArr[5];
                    var numRed6 = tdArr[6];
                    var numBlue = tdArr[7];
                    
                    var sunDay = tdArr[8];
                    var totalMoney = tdArr[9];

                    var rank1Num = tdArr[10];
                    var rank1Money = tdArr[11];
                    var rank2Num = tdArr[12];
                    var rank2Money = tdArr[13];

                    var betting = tdArr[14];
                    var lotteryDate = tdArr[15];

                    var tmp = {
                        lotteryIndex: lotteryIndex,
                        numRed1: numRed1,
                        numRed2: numRed2,
                        numRed3: numRed3,
                        numRed4: numRed4,
                        numRed5: numRed5,
                        numRed6: numRed6,
                        numBlue: numBlue,

                        sunDay: sunDay,
                        totalMoney: totalMoney,

                        rank1Num: rank1Num,
                        rank1Money: rank1Money,
                        rank2Num: rank2Num,
                        rank2Money: rank2Money,

                        betting: betting,                       
                        lotteryDate: lotteryDate
                    };
                    links.push(tmp);


                    var ssc = new SSCModel({
                        lotteryIndex :lotteryIndex,
                        numRed1: numRed1,
                        numRed2: numRed2,
                        numRed3: numRed3,
                        numRed4: numRed4,
                        numRed5: numRed5,
                        numRed6: numRed6,
                        numBlue: numBlue,

                        sunDay: sunDay,
                        totalMoney: totalMoney,

                        rank1Num: rank1Num,
                        rank1Money: rank1Money,
                        rank2Num: rank2Num,
                        rank2Money: rank2Money,

                        betting: betting,
                        lotteryDate: new Date(lotteryDate.replace(/-/g, "/"))
                    });

                    ssc.save(function (err, res) {
                        if (err) {
                            console.log("Error:" + err);
                        }
                        else {
                            console.log("Res:" + res);
                        }
                    });
                }
            });
            
            var fs = require("fs");
            var filePath = './data/shuangseqiu.json';
            fs.writeFile(filePath, JSON.stringify(links),
                function(err){
                    console.log('write file path:'+filePath+' err:'+err);
            });

            res.send({
                msg: "success",
                data: links,
                code: 1
            });
        } else {
            res.send({
                msg: "糟糕!!! 网络好像有点问题",
                code: 0
            })
        }
    });
}

app.get('/', function (req, res) {
    list(req, res)
});

app.get('/all', function (req, res) {

    //07.08.11.17.22.28+03
    // var selectSSC = new SSCModel({
    //     numRed1: "07",
    //     numRed2: "08",
    //     numRed3: "11",
    //     numRed4: "17",
    //     numRed5: "22",
    //     numRed6: "28",
    //     numBlue: "03",
    // });

    //04.13.14.19.22.31+09
    // var selectSSC = new SSCModel({
    //     numRed1: "04",
    //     numRed2: "13",
    //     numRed3: "14",
    //     numRed4: "19",
    //     numRed5: "22",
    //     numRed6: "31",
    //     numBlue: "09",
    // });

    //03.08.16.18.22.33+06
    var selectSSC = new SSCModel({
        numRed1: "03",
        numRed2: "08",
        numRed3: "16",
        numRed4: "18",
        numRed5: "22",
        numRed6: "33",
        numBlue: "06",
    });

    SSCModel.find({},function (err,sqlres) {
        if (err) {
            console.log("Error:" + err);
            res.send({
                msg: err.toString(),
                code: 0
            })
        } else {
            console.log("Res:" + sqlres);
            var links = [];

            for(var i = 0; i < sqlres.length; i++){
                var tssc = sqlres[i];

                var j = 0;
                var k = 0;
                if(selectSSC.numRed1 == tssc.numRed1){
                    j++;
                }
                if(selectSSC.numRed2 == tssc.numRed2){
                    j++;
                }
                if(selectSSC.numRed3 == tssc.numRed3){
                    j++;
                }
                if(selectSSC.numRed4 == tssc.numRed4){
                    j++;
                }
                if(selectSSC.numRed5 == tssc.numRed5){
                    j++;
                }
                if(selectSSC.numRed6 == tssc.numRed6){
                    j++;
                }
                if(selectSSC.numBlue == tssc.numBlue){
                    k++;
                }

                if (j + k >= 4){
                    links.push(tssc);
                }
            }

            res.send({
                msg: "success",
                data: links,
                code: 1
            });

        }
    });
});

module.exports = app;



